package com.zed.code.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zed.code.base.TResponse;
import com.zed.code.request.PushReqInfo;
import com.zed.code.response.ChargeDetail;
import com.zed.code.response.NChargeOrderInfoParam;
import com.zed.code.response.NEquipChargeStatusParam;
import com.zed.code.service.PushService;
import com.zed.code.service.impl.RedisHandle;
import com.zed.code.util.GDEVConfig;
import com.zed.code.util.PubFetchTool;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Controller
@RequestMapping("/v1")
public class V1PushController {
    private static Logger log = LoggerFactory.getLogger(V1PushController.class);
    @Resource
    private PushService pushService;
    @Autowired
    private RedisHandle redisHandle;

    public final static String OPERATOR_ID = "314838869"; //组织机构代码(企业名称，营业执照)：

    //订单推送
    @RequestMapping(value = "/notification_charge_order_info", method = {RequestMethod.POST})
    @ResponseBody
    private TResponse notificationChargeOrderInfo(HttpServletRequest request, HttpServletResponse response) {
        InputStream is = null;
        try {
            is = request.getInputStream();
            JSONObject bodyInfo = JSONObject.parseObject(IOUtils.toString(is, "utf-8"));
            if (null == bodyInfo) {
                return PubFetchTool.genErrorResp("4003", "POST参数不法，缺少必须的示例");
            }
            log.info("入参信息：" + bodyInfo);

            List<PushReqInfo> push = new ArrayList<PushReqInfo>();
            PushReqInfo didi = new PushReqInfo();
            JSONObject didiResult = PubFetchTool.dealParam(JSON.toJSONString(chargeOrderInfo(bodyInfo)), GDEVConfig.AES_KEY, GDEVConfig.AES_IV, GDEVConfig.SIGN_KEY);
            log.info("封装后的参数{}", JSON.toJSONString(didiResult));
            didi.setData(didiResult.toJSONString());
            didi.setMethod("notification_charge_order_info");
            didi.setOperatorSecret(GDEVConfig.OPERATOR_SECRET);
            didi.setURL(GDEVConfig.URL);
            didi.setAesKey(GDEVConfig.AES_KEY);
            didi.setAesIv(GDEVConfig.AES_IV);
            didi.setSignKey(GDEVConfig.SIGN_KEY);
            push.add(didi);

            pushService.pushToPlatform(push);
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());

            return PubFetchTool.genErrorResp("4003", "系统异常");
        }
        return new TResponse("成功");
    }


    //设备变化推送
    @RequestMapping(value = "/notification_stationStatus", method = {RequestMethod.POST})
    @ResponseBody
    private TResponse notificationStationStatus(HttpServletRequest request, HttpServletResponse response) {
        InputStream is = null;
        try {
            is = request.getInputStream();
            JSONObject bodyInfo = JSONObject.parseObject(IOUtils.toString(is, "utf-8"));
            if (null == bodyInfo) {
                return PubFetchTool.genErrorResp("4003", "POST参数不合法，缺少必须的示例");
            }
            log.info("入参信息：{}", bodyInfo);
            List<PushReqInfo> push = new ArrayList<PushReqInfo>();

            PushReqInfo didi = new PushReqInfo();
            JSONObject didiResult = PubFetchTool.dealParam(JSON.toJSONString(stationStatus(bodyInfo)), GDEVConfig.AES_KEY, GDEVConfig.AES_IV, GDEVConfig.SIGN_KEY);
            log.info("封装后的参数{}", JSON.toJSONString(didiResult));
            didi.setData(didiResult.toJSONString());
            didi.setMethod("notification_stationStatus");
            didi.setOperatorSecret(GDEVConfig.OPERATOR_SECRET);
            didi.setURL(GDEVConfig.URL);
            didi.setAesKey(GDEVConfig.AES_KEY);
            didi.setAesIv(GDEVConfig.AES_IV);
            didi.setSignKey(GDEVConfig.SIGN_KEY);
            push.add(didi);
            pushService.pushToPlatform(push);
            return new TResponse("成功");
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            return PubFetchTool.genErrorResp("4003", "系统异常");
        }
    }
    //订单状态推送
    @RequestMapping(value = "/notification_equip_charge_status", method = {RequestMethod.POST})
    @ResponseBody
    private TResponse notificationEquipChargeStatus(HttpServletRequest request, HttpServletResponse response) {
        InputStream is = null;
        try {
            is = request.getInputStream();
            JSONObject bodyInfo = JSONObject.parseObject(IOUtils.toString(is, "utf-8"));
            if (null == bodyInfo) {
                return PubFetchTool.genErrorResp("4003", "POST参数不合法，缺少必须的示例");
            }
            log.info("入参信息：{}", bodyInfo);
            List<PushReqInfo> push = new ArrayList<PushReqInfo>();

            PushReqInfo didi = new PushReqInfo();
            JSONObject didiResult = PubFetchTool.dealParam(JSON.toJSONString(equipChargeStatus(bodyInfo)), GDEVConfig.AES_KEY, GDEVConfig.AES_IV, GDEVConfig.SIGN_KEY);
            log.info("封装后的参数{}", JSON.toJSONString(didiResult));
            didi.setData(didiResult.toJSONString());
            didi.setMethod("notification_equip_charge_status");
            didi.setOperatorSecret(GDEVConfig.OPERATOR_SECRET);
            didi.setURL(GDEVConfig.URL);
            didi.setAesKey(GDEVConfig.AES_KEY);
            didi.setAesIv(GDEVConfig.AES_IV);
            didi.setSignKey(GDEVConfig.SIGN_KEY);
            push.add(didi);
            pushService.pushToPlatform(push);


            return new TResponse("成功");
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            return PubFetchTool.genErrorResp("4003", "系统异常");
        }
    }
    private NEquipChargeStatusParam equipChargeStatus(JSONObject bodyInfo) throws Exception {
        NEquipChargeStatusParam nEquipChargeStatusParam = new NEquipChargeStatusParam();
        String orderId = bodyInfo.getString("StartChargeSeq");

        Integer StartChargeSeqStat= bodyInfo.getInteger("StartChargeSeqStat");
        //判断
        if (StartChargeSeqStat==null){
            throw new Exception("数据错误");
        }else if (StartChargeSeqStat==1){//启动中
            redisHandle.addList("OrderChargeStatus",orderId);
        }else {
            redisHandle.removeListValue("OrderChargeStatus",orderId);
        }

        if (orderId.length()!=27){//平台自己的订单
            orderId=OPERATOR_ID+"000"+orderId;
        }
        nEquipChargeStatusParam.setStartChargeSeq(orderId);
        nEquipChargeStatusParam.setStartChargeSeqStat(bodyInfo.getInteger("StartChargeSeqStat"));
        nEquipChargeStatusParam.setConnectorID(bodyInfo.getString("ConnectorID"));
        nEquipChargeStatusParam.setConnectorStatus(bodyInfo.getString("ConnectorStatus"));
        nEquipChargeStatusParam.setCurrentA(bodyInfo.getFloat("CurrentA"));
        nEquipChargeStatusParam.setCurrentB(bodyInfo.getFloat("CurrentB"));
        nEquipChargeStatusParam.setCurrentC(bodyInfo.getFloat("CurrentC"));
        nEquipChargeStatusParam.setVoltageA(bodyInfo.getFloat("VoltageA"));
        nEquipChargeStatusParam.setVoltageB(bodyInfo.getFloat("VoltageB"));
        nEquipChargeStatusParam.setVoltageC(bodyInfo.getFloat("VoltageC"));
        nEquipChargeStatusParam.setSoc(bodyInfo.getFloat("Soc"));
        nEquipChargeStatusParam.setStartTime(bodyInfo.getString("StartTime"));
        nEquipChargeStatusParam.setChargeModel(bodyInfo.getInteger("ChargeModel"));
        nEquipChargeStatusParam.setEndTime(bodyInfo.getString("EndTime"));
        nEquipChargeStatusParam.setTotalPower(bodyInfo.getFloat("TotalPower"));
        nEquipChargeStatusParam.setElecMoney(bodyInfo.getFloat("ElecMoney"));
        nEquipChargeStatusParam.setSeviceMoney(bodyInfo.getFloat("SeviceMoney"));
        nEquipChargeStatusParam.setTotalMoney(bodyInfo.getFloat("TotalMoney"));
        nEquipChargeStatusParam.setSumPeriod(bodyInfo.getInteger("SumPeriod"));
        JSONArray chargeDetails= bodyInfo.getJSONArray("ChargeDetails");

        List<ChargeDetail> chargeDetails2=JSONArray.parseArray(chargeDetails.toJSONString(),ChargeDetail.class);
        nEquipChargeStatusParam.setChargeDetails(chargeDetails2);
        return nEquipChargeStatusParam;
    }
    private NChargeOrderInfoParam chargeOrderInfo(JSONObject bodyInfo) {
        NChargeOrderInfoParam nChargeOrderInfoParam = new NChargeOrderInfoParam();
        nChargeOrderInfoParam.setConnectorID(bodyInfo.getString("ConnectorID"));

        String orderId = bodyInfo.getString("StartChargeSeq");
        if (orderId.length()!=27){//平台自己的订单
            orderId=OPERATOR_ID+"000"+orderId;
        }
        nChargeOrderInfoParam.setStartChargeSeq(orderId);
        nChargeOrderInfoParam.setStartTime(bodyInfo.getString("StartTime"));
        nChargeOrderInfoParam.setEndTime(bodyInfo.getString("EndTime"));
        nChargeOrderInfoParam.setTotalPower(bodyInfo.getFloatValue("Elect"));
        nChargeOrderInfoParam.setTotalElecMoney(bodyInfo.getFloatValue("ElectMoney"));
        nChargeOrderInfoParam.setTotalServiceMoney(bodyInfo.getFloatValue("ServiceMoney"));
        nChargeOrderInfoParam.setTotalMoney(bodyInfo.getFloatValue("Money"));
        nChargeOrderInfoParam.setStopReason(bodyInfo.getIntValue("StopReason"));
        Integer PayChannel = bodyInfo.getIntValue("PayChannel");
        nChargeOrderInfoParam.setChargeModel(PayChannel == 4 ? 2 : 3);
        nChargeOrderInfoParam.setVin("");
        nChargeOrderInfoParam.setSumPeriod(0);
        nChargeOrderInfoParam.setChargeDetails(new ArrayList<ChargeDetail>());
        return nChargeOrderInfoParam;
    }
    private Map stationStatus(JSONObject bodyInfo) {
        String connectorID = bodyInfo.getString("ConnectorID");
        Integer status = bodyInfo.getInteger("Status");
        Map req = new HashMap();
        req.put("ConnectorID", connectorID);
        req.put("Status", status);
        req.put("CurrentA", 0);
        req.put("CurrentB", 0);
        req.put("CurrentC", 0);
        req.put("VoltageA", 0);
        req.put("VoltageB", 0);
        req.put("VoltageC", 0);
        req.put("ParkStatus", 0);
        req.put("LockStatus", 0);
        req.put("SOC", 0);
        Map reqInfo = new HashMap();
        reqInfo.put("ConnectorStatusInfo", req);
        return reqInfo;
    }
}
